from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import AIN_User_Package, AIN_Package, AIN_Presubscription, AIN_Extra_Data_Package, AIN_Promotion_Package
from datetime import datetime, timedelta
import json
import random
import string

def generate_unique_code(existing_codes, length=12, blocks=3, separator='-'):
    chars = string.ascii_uppercase + string.digits
    while True:
        code = ''.join(random.choice(chars) for _ in range(length))
        if separator:
            code = separator.join(code[i:i + length // blocks] for i in range(0, length, length // blocks))
        if code not in existing_codes:
            return code

@csrf_exempt
def purchase(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        uuid = data['uuid']
        package_type = data['package_type']
        if purchase_in_db(uuid, package_type):
            return JsonResponse({'message': 'Whisper time and package type updated successfully, and new package created!'})
        else:
            return JsonResponse({'message': 'Failed to update whisper time and create new package.'}, status=500)

def purchase_in_db(uuid, package_type):
    try:
        now = datetime.now()
        now_plus_30_days = now + timedelta(days=30)

        user_package = AIN_User_Package.objects.get(uuid=uuid)
        user_package.is_new = True
        if not user_package.is_active:
            user_package.is_active = True
            user_package.whisper_time = (user_package.whisper_time or 0) + 100
            user_package.package_type = package_type
            user_package.package_starting_time = now
            user_package.package_completing_time = now_plus_30_days
        else:
            user_package.package_type = package_type
        user_package.save()

        AIN_Package.objects.create(uuid=uuid, package_type=package_type, create_time=now)

        presub, created = AIN_Presubscription.objects.get_or_create(uuid=uuid)
        if created:
            presub.month_duration = 1
            presub.package_type = package_type
        else:
            presub.month_duration += 1
            presub.package_type = package_type
        presub.save()

        return True
    except Exception as e:
        print(f"Failed to update whisper time and insert package: {e}")
        return False

@csrf_exempt
def add_user(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        new_uuid = data['new_uuid']
        if add_user_in_db(new_uuid):
            return JsonResponse({'message': 'User added successfully!'})
        else:
            return JsonResponse({'message': 'Failed to add user.'}, status=500)

def add_user_in_db(uuid):
    try:
        AIN_User_Package.objects.create(uuid=uuid)
        return True
    except Exception as e:
        print(f"Failed to add user: {e}")
        return False

# 其他视图函数类似，包括购买额外数据包、生成推广码、分发推广码和更新数据
